package com.corpgovernment.organization.service.impl;

import com.corpgovernment.api.applytrip.vo.AoApplyTripTempVo;
import com.corpgovernment.api.organization.dto.SwitchInfoDto;
import com.corpgovernment.api.organization.enums.SwitchEnum;
import com.corpgovernment.api.organization.model.switchinfo.GetAllSwitchResponse;
import com.corpgovernment.api.organization.model.switchinfo.GetSwitchListResponse;
import com.corpgovernment.api.organization.model.switchinfo.SwitchInfoSoa;
import com.corpgovernment.api.organization.model.switchinfo.SwitchInfoVo;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.corpgovernment.organization.dataloader.ApplyTripClientLoader;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.entity.db.MbOrgSwitchRelation;
import com.corpgovernment.organization.entity.db.MbOrgTravelAttributeRelation;
import com.corpgovernment.organization.mapper.MbOrgTravelAttributeRelationMapper;
import com.corpgovernment.organization.model.SwitchConfigInfo;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zl.cui
 * @date 2023/8/21
 */
@Service
@Slf4j
public class GetAllSwitchService {
    @Autowired
    private OrganizationApollo organizationApollo;
    @Autowired
    private MbOrgTravelAttributeRelationMapper mbOrgTravelAttributeRelationMapper;
    @Autowired
    private ApplyTripClientLoader applyTripClientLoader;
    @Autowired
    private IOrganizationInfoService organizationInfoService;
    public GetAllSwitchResponse allSwitch(String orgId, String uid) {
        GetAllSwitchResponse response = new GetAllSwitchResponse();
        response.setUrgentEnable(null);
        GetSwitchListResponse getSwitchListResponse = new GetSwitchListResponse();
        getSwitchListResponse.setOrgId(orgId);
        response.setOrgId(orgId);
        response.setUId(uid);
        List<SwitchInfoDto> defaultSwitchList = null;
        //apollo 查询开关默认值
        defaultSwitchList = builderDefaultSwitchData(getSwitchListResponse);
        Map<String, SwitchInfoDto> defaultSwitchMap = defaultSwitchList.stream().collect(Collectors.toMap(x -> x.getKey(), x -> x, (k1, k2) -> k1));
        List<SwitchInfoVo> allSwitch = new ArrayList<>();
        List<SwitchInfoSoa> allSwitchSoa = new ArrayList<>();
        log.info("查询默认的差旅属性：{}", JsonUtils.toJsonString(defaultSwitchList));
        MbOrgSwitchRelation switchRelationParam = new MbOrgSwitchRelation();
        // 获取上级公司的配置
        MbOrgInfo corpInfo = organizationInfoService.findFirstCompany(orgId);
        switchRelationParam.setOrgId(corpInfo.getOrgId());
        List<MbOrgTravelAttributeRelation> switchRelations = mbOrgTravelAttributeRelationMapper.getSwitchRelation(switchRelationParam.getOrgId(), switchRelationParam.getUId());
        log.info("配置的差旅属性：{}", JsonUtils.toJsonString(switchRelations));
        SwitchInfoSoa switchInfoSoa = null;
        if (!CollectionUtils.isEmpty(switchRelations)) {
            //匹配开关和值
            SwitchInfoVo switchInfoVo = null;
            for (MbOrgTravelAttributeRelation orgSwitchRelation : switchRelations) {
                switchInfoVo = new SwitchInfoVo();
                switchInfoSoa = new SwitchInfoSoa();
                switchInfoVo.setKey(orgSwitchRelation.getSwitchKey());
                switchInfoVo.setId(orgSwitchRelation.getId());
                switchInfoVo.setName(orgSwitchRelation.getSwitchName());
                SwitchInfoDto switchInfoDto = defaultSwitchMap.get(orgSwitchRelation.getSwitchKey());
                if (switchInfoDto != null && switchInfoDto.getShowFlag()) {
                    switchInfoVo.setAllValues(switchInfoDto.getAllValues());
                    if (!StringUtils.isBlank(orgSwitchRelation.getAllValues())) {
                        switchInfoVo.setAllValues(JsonUtils.parseMap(orgSwitchRelation.getAllValues()));
                    }
                    switchInfoVo.setNowVal(JsonUtils.parseArray(orgSwitchRelation.getValue(), Object.class));
                    allSwitch.add(switchInfoVo);
                }
                BeanUtils.copyProperties(orgSwitchRelation, switchInfoSoa);
                switchInfoSoa.setSwitchId(orgSwitchRelation.getId());
                if (!StringUtils.isBlank(orgSwitchRelation.getAllValues())) {
                    switchInfoSoa.setAllValues((JsonUtils.parseMap(orgSwitchRelation.getAllValues())));
                }
                allSwitchSoa.add(switchInfoSoa);
            }
        }
        Map<String, SwitchInfoVo> allSwitchMap = allSwitch.stream().collect(Collectors.toMap(SwitchInfoVo::getKey, x -> x, (k1, k2) -> k2));
        //增加默认初始值的开关
        if (!CollectionUtils.isEmpty(defaultSwitchList)) {
            SwitchInfoVo data = null;
            for (SwitchInfoDto switchInfoDto : defaultSwitchList) {
                data = allSwitchMap.get(switchInfoDto.getKey());
                if (data == null) {
                    switchInfoDto.setOrgId(orgId);
                    switchInfoSoa = new SwitchInfoSoa();
                    switchInfoSoa.setOrgId(orgId);
                    switchInfoSoa.setSwitchId(switchInfoDto.getId());
                    switchInfoSoa.setSwitchKey(switchInfoDto.getKey());
                    switchInfoSoa.setSwitchName(switchInfoDto.getName());
                    switchInfoSoa.setValue(JsonUtils.toJsonString(switchInfoDto.getNowVal()));
                    switchInfoSoa.setAllValues(switchInfoDto.getAllValues());

                    allSwitchSoa.add(switchInfoSoa);
                }
            }
        }
        response.setSwitchInfoSoaList(allSwitchSoa);
        response.setSwitchInfoSoaMap(allSwitchSoa.stream().filter(x -> !StringUtils.isBlank(x.getSwitchKey())).collect(Collectors.toMap(x -> x.getSwitchKey(), x -> x, (k1, k2) -> k2)));
        return response;
    }

    /**
     * 获取配置key的list
     *
     * @return
     */
    private List<SwitchInfoDto> builderDefaultSwitchData(GetSwitchListResponse response) {
        List<SwitchConfigInfo> switchConfigInfos = JsonUtils.parseArray(organizationApollo.getConfigSwitchinfoList(), SwitchConfigInfo.class);
        List<SwitchInfoDto> switchInfoList = new ArrayList<>();
        if (switchConfigInfos == null) {
            return switchInfoList;
        }
        for (SwitchConfigInfo switchConfigInfo : switchConfigInfos) {
            SwitchInfoDto switchInfoDto = new SwitchInfoDto();
            switchInfoDto.setNowVal(switchConfigInfo.getDefaultVal());
            switchInfoDto.setName(switchConfigInfo.getName());
            switchInfoDto.setAllValues(switchConfigInfo.getAllValues());
            switchInfoDto.setKey(switchConfigInfo.getKey());
            switchInfoDto.setShowFlag(switchConfigInfo.getShowFlag());
            switchInfoDto.setSort(switchConfigInfo.getSort());
            //获取出差申请模版列表
            if (SwitchEnum.APPLICATION_TEMPLATE.getKey().equals(switchConfigInfo.getKey())) {
                //switchInfoDto.setAllValues(getApplyTripTemplateList(response.getOrgId()));
            }

            switchInfoList.add(switchInfoDto);
        }
        return switchInfoList;
    }

    /**
     * 获取出差申请模版列表
     *
     * @return
     */
    private Map<String, Object> getApplyTripTemplateList(String orgId) {
        List<AoApplyTripTempVo> aoApplyTripTempList = applyTripClientLoader.listApplyTripTempList(orgId);
        if (CollectionUtils.isEmpty(aoApplyTripTempList)) {
            return new HashMap<>();
        }
        Map<String, Object> map = new HashMap<>();
        for (AoApplyTripTempVo item : aoApplyTripTempList) {
            map.put(item.getId().toString(), item.getTempName());
        }
        return map;
    }
}
